﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ADO.NET_2
{
    class DBHelper
    {
        //连接
        private SqlConnection GetSqlConnection()
        {
            //连接字符串
            string connStr = "server = . ; database = dbdemo ; uid = sa ; pwd = 193746";
            //声明连接对象
            SqlConnection conn = new SqlConnection(connStr);
            return conn;
        }
        //输出userInfo
        public DataTable PrintUserInfo()
        {
            //获得连接
            SqlConnection conn = GetSqlConnection();
            //打开连接
            conn.Open();
            //sql查询语句
            string query = "SELECT * FROM userInfo";
            //声明适配器对象
            SqlDataAdapter sda = new SqlDataAdapter(query, conn);
            //声明数据表对象
            DataTable dt = new DataTable();
            //将查询出来的数据填充至dt中
            sda.Fill(dt);
            //断开连接
            conn.Close();
            //输出查询结果
            Console.WriteLine("用户名" + "\t" + "密码" + "\t" + "年龄" + "\t" + "性别"); //增加标识行
            for (int i = 0;i < dt.Rows.Count;i++)
            {
                //将dt的每一行数据提取至DataRow中
                DataRow dr = dt.Rows[i];
                string userName = (string)dr["userName"]; //将Object强转为string
                string userPwd = (string)dr["userPwd"];
                int userAge = (int)dr["userAge"];
                string userSex = (string)dr["userSex"];
                //打印
                Console.WriteLine(userName + "\t" + userPwd + "\t" + userAge + "\t" + userSex);
            }
            return dt;
        }
    }
}
